package cn.vendpay.com.task;

import cn.vendpay.com.mapper.VideoMapper;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;


@Slf4j
@Component
public class VideoDeleteTask {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private VideoMapper videoMapper;

    @Value("${minio.bucket}")
    private String bucketName;

    @Value("${minio.batchSize:20}")
    private int batchSize;

    @Scheduled(cron = "0 0 * * * ?") // 每小时整点执行一次
    public void deleteVideos() {
        // 每次处理 20 个待删除视频
        List<String> urls = videoMapper.getDeletedVideos(batchSize);
        for (String url : urls) {
            try {
                // 先删除 MinIO
                minioClient.removeObject(
                        RemoveObjectArgs.builder()
                                .bucket(bucketName)
                                .object(url)
                                .build()
                );
                // 删除数据库记录
                videoMapper.deleteByUrl(url);
            } catch (Exception e) {
                // 打日志，留待下次重试
                log.error("删除视频失败: " + url, e);
            }
        }
    }
}
